package edu.cuit.zhuyimeng.ticket.config;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.CacheManager;
import com.alicp.jetcache.anno.CacheConsts;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.template.QuickConfig;
import edu.cuit.zhuyimeng.flight.api.dto.FlightInfoDTO;
import edu.cuit.zhuyimeng.framework.cache.util.CacheUtils;
import edu.cuit.zhuyimeng.ticket.controller.vo.TicketInfoVO;
import edu.cuit.zhuyimeng.ticket.enums.CacheConstants;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 缓存配置类
 */
@Configuration
@RequiredArgsConstructor
public class CacheConfig {

    private final CacheManager cacheManager;

    private Cache<String, TicketInfoVO> ticketInfoCache;

    private Cache<Long, FlightInfoDTO> flightInfoCache;

    private Cache<Long,Integer> remainTicketCache;

    private Cache<Long, Date> bookingFlightCache;

    @PostConstruct
    public void init() {
        ticketInfoCache = createCache(CacheConstants.TICKET_INFO);
        flightInfoCache = createCache(CacheConstants.FLIGHT_INFO);
        remainTicketCache = cacheManager.getOrCreateCache(QuickConfig.newBuilder(CacheConsts.DEFAULT_AREA,CacheConstants.TICKET_AMOUNT)
                .cacheType(CacheType.REMOTE)
                .expire(Duration.ofDays(1))
                .build());
        bookingFlightCache = cacheManager.getOrCreateCache(QuickConfig.newBuilder(CacheConsts.DEFAULT_AREA,CacheConstants.BOOKING_FLIGHT)
                        .cacheType(CacheType.REMOTE)
                        .cacheNullValue(false)
                        .expire(Duration.ofDays(30))
                .build());
    }


    @Bean
    public Cache<String, TicketInfoVO> ticketInfoCache() {
        return ticketInfoCache;
    }

    @Bean
    public Cache<Long, FlightInfoDTO> flightInfoCache() {
        return flightInfoCache;
    }

    @Bean
    public Cache<Long,Integer> remainTicketCache() {
        return remainTicketCache;
    }

    @Bean
    public Cache<Long,Date> bookingFlightCache() {
        return bookingFlightCache;
    }

    private <A,B> Cache<A,B> createCache(String name) {
        return cacheManager.getOrCreateCache(CacheUtils.createCommonCache(name));
    }

}
